<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\Db;
use think\Log;

// 应用公共文件
const CHBM = 1;
const HYJG = 2;
const JQ_SH_BG = 3;
const JQ_DD_BG = 4;
const JQ_SHY_BG = 5;

/**
 * 返回跨域JSON数据
 * @param type $result
 */
function json_api($data){
    return json($data,200,array(
        "Access-Control-Allow-Origin"=>" *",
        "Access-Control-Allow-Headers"=>" Origin, X-Requested-With, Content-Type, Accept",
        "Access-Control-Allow-Methods"=>" GET, POST, PUT",
        /*"Content-Type:application/json"=>" charset=utf-8"*/
    ));
}

function _array_column(array $array, $column_key, $index_key=null){
    $result = [];
    foreach($array as $arr) {
        if(!is_array($arr)) continue;

        if(is_null($column_key)){
            $value = $arr;
        }else{
            $value = $arr[$column_key];
        }

        if(!is_null($index_key)){
            $key = $arr[$index_key];
            $result[$key] = $value;
        }else{
            $result[] = $value;
        }
    }
    return $result; 
}

//致远消息推送
function send_msg($creation_date, $noneBindingSender, $noneBindingReceiver, $type = null, $messageContent, $messageURL)
{

    // $envConfig=env_config();
    // if(!empty($envConfig)&&$envConfig["env"]=="local") return false;
    //获取致远token
    $token = getToken();
    $secret = md5('321');
    //通知链接转换
    $messageURL = urlencode(str_replace('1:','',$messageURL));
    //查询、拆分接收人
    // Db::table('think_user')->where('id',1)->find();

    $sned = Db::table('user')->where(['user_id'=>$noneBindingSender])->field('remark')->find();
    // $where['user_id'] = $noneBindingReceiver;
    $user = Db::table('user')->where(['user_id' => ['in', $noneBindingReceiver]])->select();
    $user = $user->toArray();
    // $sned = $this->select_one('user',"remark","user_id = '$noneBindingSender' ");
    // $user = $this->select_raw('user',"remark,BYNAME","FIND_IN_SET(user_id,'$noneBindingReceiver')");

    $config = get_config(array("keys"=>['sms','oa_url','smsl']));

    if(count($user) == '1'){
        /*$url = $this->select_one('dev_config_params','cfg_val',"cfg_key = 'sms' ");
        $url = $url['cfg_val'].$token;*/
        $url=$config["sms"].$token;
        foreach($user as $v){
            $id = date("YmdHis").rand(100, 999);
            if(!empty($MURL) || isset($MURL));$MURL = '';
            $MURL = $config["oa_url"]."authLogin.php?u=".md5($v['BYNAME'])."&k=".$secret."&m=".$messageURL;
            $params = array(
                "thirdpartyRegisterCode" => "3001",
                "creation_date" => $creation_date,
                "thirdpartyMessageId" => $id,
                "thirdpartyReceiverId" => "1",
                "thirdpartySenderId" => "2",
                "messageURL" => $MURL,
                "messageType" => "4",
                "noneBindingSender" => $sned['remark'],
                "noneBindingReceiver" => $v['REMARK'],
                "messageContent" => $messageContent
            );
            // $params = json_encode(string::autoCharset($params,'gbk','utf-8'));
            $params = json_encode($params);
            // https_request($url,$params);
        }
    }
    if(count($user) > '1'){
        $url=$config["smsl"].$token;
        $p['messages'] = [];
        foreach($user as $v){
            $id = date("YmdHis").rand(100, 999);
            if(!empty($MURL) || isset($MURL));$MURL = '';
            $MURL = $config["oa_url"]."authLogin.php?u=".md5($v['BYNAME'])."&k=".$secret."&m=".$messageURL;
            $p['messages'][] = array(
                "thirdpartyRegisterCode" => "3001",
                "creation_date" => $creation_date,
                "thirdpartyMessageId" => $id,
                "thirdpartyReceiverId" => "1",
                "thirdpartySenderId" => "2",
                "messageURL" => $MURL,
                "messageType" => "4",
                "noneBindingSender" => $sned['remark'],
                "noneBindingReceiver" => $v['REMARK'],
                "messageContent" => $messageContent
            );
        }
        $params = json_encode($params);
        // https_request($url,$params);
    }
    echo $params;

}

function getToken(){
    $url = db('config_params')->where(['cfg_key'=>'token'])->field('cfg_val')->find();
    $rest = db('config_params')->where(['cfg_key'=>'token'])->field('cfg_val')->find();
    $params = json_encode(array('userName' => 'rest', 'password' => $rest['cfg_val'],'loginName'=>'oa1'));
    $res = https_request($url['cfg_val'], $params);
    $result = json_decode($res, true);
    return $result['id'];
}

function https_request($url, $params = null)
{
    $curl = curl_init();    // curl 设置
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($params)
    ));
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);  // 校验证书节点
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);// 校验证书主机

    // 判断 $data get  or post
    if (!empty($params)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
    }
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  // 以文件流的形式 把参数返回进来
    // 执行
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
}

function get_config($params){
    if(empty($params["keys"])) return false;
    $dataList = db('config_params')->where('cfg_key', 'in', $params["keys"])->select();
    // $dataList = $this->select_raw('dev_config_params','*',"cfg_key in({$params["keys"]}) ");
    if(empty($dataList))return false;
    $retArray=array();
    foreach ($dataList as $key=>$val){
        $retArray[$val["cfg_key"]]=$val["cfg_val"];
    }
    return $retArray;
}

//发送消息
function send_message($FROM_ID, $TO_ID, $CONTENT, $REMIND_URL){
    // sms_open
    $smsOpen = config('sms_open');
    if ($smsOpen) {
        $sendUrl = 'erp_sms.php';
    } else {
        $sendUrl = 'td_sms.php';
    }
    Log::record("SEND_MESSAGE_INFO1: FROM_ID:". $FROM_ID . " TO_ID:". $TO_ID. " CONTENT:". $CONTENT. " REMIND_URL:". $REMIND_URL);
    $userInfo1 = Db::table('user')->where(['UID'=>$FROM_ID])->find();
    if (!empty($userInfo1)) {
        $FROM_ID = $userInfo1['USER_ID'];
    }
    $userInfo2 = Db::table('user')->where(['UID'=>$TO_ID])->find();
    if (!empty($userInfo2)) {
        $TO_ID = $userInfo2['USER_ID']; 
    }
    $host = $_SERVER['HTTP_HOST'];
    $ch = curl_init();
    $url = $host. "/general/jigang_sms/".$sendUrl."?fromId=".$FROM_ID."&toId=".$TO_ID."&content=".$CONTENT."&remindUrl=".$REMIND_URL;
    Log::record("SEND_MESSAGE_INFO2:".$url);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_exec($ch);
    curl_close($ch);
}